package online.duanqing.authorization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import online.duanqing.authorization.bean.UserLoginInfo;
import online.duanqing.authorization.mapper.UserLoginInfoMapper;
import online.duanqing.authorization.service.UserLoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with hz
 *
 * @Author: DQ
 * @Date: 2024/01/16/14:04
 * @Description: 描述语句
 */
@Service
public class UserLoginInfoServiceImpl implements UserLoginInfoService {



    @Resource
    private UserLoginInfoMapper userLoginInfoMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        LambdaQueryWrapper<UserLoginInfo> query = new LambdaQueryWrapper<>();
        boolean exists = userLoginInfoMapper.exists(query.eq(UserLoginInfo::getUserName, username));
        if (exists){
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            UserLoginInfo userLoginInfo = userLoginInfoMapper.selectOne(query);
            return new User(username,bCryptPasswordEncoder.encode(userLoginInfo.getPassword()),authorities);
        }else {
            System.out.println(username);
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
    }
}
